#!/usr/bin/env python

from __future__ import with_statement

import wx
import model
import datetime
import threading
import messaging.sms

from autorm.db.query import Query

class Messages(object):
    '''Messages class
    
    @author Julot <andy.julot@gmail.com>
    @since Friday, February 24, 2012. 10:12 AM'''
    
    def __init__(self, view, interactor):
        self.view = view
        self.interactor = interactor
        self.setLabels()
    
    def setLabels(self):
        '''Set navigation label'''
        
        labels = [model.Message.LABEL_INBOX.capitalize(),
                  model.Message.LABEL_ARCHIVE.capitalize(),
                  model.Message.LABEL_TRASH.capitalize(),
                  model.Message.LABEL_OUTBOX.capitalize(),
                  model.Message.LABEL_SENT.capitalize()]
        self.view.messages.labels.values = labels
    
    def loadModel(self, id):
        return model.Message.get(id)
    
    def show(self, index, id):
        sms = self.loadModel(id)
        if not sms.seen:
            sms.seen = True
            sms.save()
        
        attributes = sms.attributes
        attributes.index = index
        attributes.completeMessage = sms.completeMessage
        self.view.messages.message.model = attributes
        self.view.message.model = attributes
        
        menu = self.view.MenuBar
        tool = self.view.messages.toolBar
        b = sms.LABEL_ARCHIVE in sms.labels or sms.LABEL_TRASH in sms.labels
        menu.message.archive.Enable(not b)
        tool.archive.enable(not b)
        b = sms.LABEL_TRASH in sms.labels
        menu.message.delete.Enable(not b)
        tool.delete.enable(not b)
        menu.message.recover.Enable(b)
        tool.recover.enable(b)
    
    def filter(self, value):
        value = value.lower()
        self.view.busyInfo('Loading message...')
        with threading.RLock():
            query = model.Message.objects.query()
            query.order_by('dateTime', 'desc')
            # This is using modified autorm with regular expression addition
            if value in (model.Message.LABEL_INBOX, model.Message.LABEL_OUTBOX):
                query.filter(labels=value, sequence__lt=2)
            elif value in (model.Message.LABEL_ARCHIVE, model.Message.LABEL_SENT):
                trash = model.Message.LABEL_TRASH
                query.filter(labels__regexp=r'\b%s\b' % value, sequence__lt=2,
                             labels__notregexp=r'\b%s\b' % trash)
            else:
                query.filter(labels__regexp=r'\b%s\b' % value, sequence__lt=2)
            self.view.messages.messages.values = query
        self.view.idle()
    
    def archive(self):
        attributes = self.view.messages.message.model
        self.view.messages.messages.DeleteItem(attributes.index)
        self.view.MenuBar.message.archive.Enable(False)
        self.view.messages.toolBar.archive.disable()
        self.view.MenuBar.message.delete.Enable(False)
        self.view.messages.toolBar.delete.disable()
        self.view.messages.message.model = None
        self.view.message.model = None
        with threading.RLock():
            sms = self.loadModel(attributes.id)
            sms.archive()
    
    def delete(self):
        attributes = self.view.messages.message.model
        self.view.messages.messages.DeleteItem(attributes.index)
        self.view.MenuBar.message.archive.Enable(False)
        self.view.messages.toolBar.archive.disable()
        self.view.MenuBar.message.delete.Enable(False)
        self.view.messages.toolBar.delete.disable()
        self.view.MenuBar.message.recover.Enable(False)
        self.view.messages.toolBar.recover.disable()
        self.view.messages.message.model = None
        self.view.message.model = None
        with threading.RLock():
            sms = self.loadModel(attributes.id)
            sms.trash()
    
    def recover(self):
        attributes = self.view.messages.message.model
        self.view.messages.messages.DeleteItem(attributes.index)
        self.view.MenuBar.message.recover.Enable(False)
        self.view.messages.toolBar.recover.disable()
        self.view.messages.message.model = None
        self.view.message.model = None
        with threading.RLock():
            sms = self.loadModel(attributes.id)
            sms.recover()
    
    def confirmExport(self):
        wildcard = 'Excel files (*.xls)|*.xls'
        s = datetime.datetime.now().strftime('%Y-%m-%d %H-%M')
        defaultFile = 'SMS %s.xls' % s
        style = wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT
        return self.view.fileDialog(defaultFile=defaultFile, wildcard=wildcard,
                                    style=style)
    
    def export(self, path):
        self.view.busyInfo('Exporting data...')
        with threading.RLock(): model.Message.toExcel(path)
        self.view.idle()
